<template>
  <div style="background: #fff;">
    <a-table
      :columns="columns"
      :row-key="rowKey"
      :data-source="tableData"
      bordered
      size="small"
      :pagination="false"
    >
      <template>
        <span
          v-for="(item, index) in columns"
          :key="item.dataIndex"
          :slot="item.dataIndex + 'Title'"
        ><span style="color: red;">*</span>{{ item.titleName }}</span>
      </template>
      
      <template
        v-for="(col, index) in columns"
        :slot="col.dataIndex"
        slot-scope="text, record, index"
      >
        <div
          :key="col.dataIndex"
          :ref="record[rowKey]+col.dataIndex"
          class=""
        >
          <template v-if="editable">
            <template v-if="col.editType == 'input'">
              <a-input
                :max-length="30"
                style="margin: -5px 0"
                :value="text"
                @change="e => handleChange(e.target.value, record[rowKey], col.dataIndex)"
              />
            </template>
            <template v-else-if="col.editType == 'select'">
              <a-select
                :value="text ? text : {}"
                style="width: 100%" 
                :get-popup-container="getPopupContainer"
                label-in-value
                @change="(val, opt) => handleChange(val, record[rowKey], col.dataIndex, col.dataIndex)"
              >
                <a-select-option
                  v-for="(item, idx) in col.selectData" 
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </template>
            <template v-else-if="col.editType == 'number'">
              <!-- :formatter="(e) => integerFormat(e, col.dataIndex)" -->
              <a-input-number
                :min="col.minNumber !== undefined ? col.minNumber : 1"
                :precision="col.dataIndex == 'meetingBudget' ? 2 : 0"
                :value="text" 
                @change="e => handleChange(e, record[rowKey], col.dataIndex)"
              />
            </template>
            <template v-else-if="col.editType == 'date'">
              <a-date-picker
                :default-picker-value="year + moment().format('-MM-DD')"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                value-format="YYYY-MM-DD"
                :allow-clear="false"
                :value="text"
                @change="e => handleChange(e, record[rowKey], col.dataIndex)"
              >
                <!-- @change="e => handleChange(moment(e).format('YYYY.MM.DD'), record[rowKey], col.dataIndex)" -->
                <a-icon
                  slot="suffixIcon"
                  type="calendar"
                  style="color: #40a9ff;"
                />
              </a-date-picker>
            </template>
          </template>
          <template v-else>
            <template v-if="col.dataIndex == 'meetingType'">
              {{ text ? text.label : '' }}
            </template>
            <template v-else-if="col.dataIndex == 'meetingRoom'">
              {{ text ? text.label : '' }}
            </template>
            <template v-else-if="col.dataIndex == 'meetingForm'">
              {{ text ? text.label : '' }}
            </template>
            <template v-else>
              {{ text }}
            </template>
          </template>
        </div>
      </template>
      
      <template
        slot="serial"
        slot-scope="text, record, index"
      >
        {{ index + 1 }}
      </template>
      
      <template
        slot="operation"
        slot-scope="text, record, index"
      >
        <div class="editable-row-operations">
          <!-- <span v-if="editable">
            <a @click="() => save(record[rowKey])">保存</a>
          </span>
          <span v-else>
            <a :disabled="editingKey !== ''" @click="() => edit(record[rowKey])">编辑</a>
          </span> -->
          <span>
            <a-popconfirm
              title="是否要删除该行数据?"
              @confirm="() => del(record[rowKey])"
            >
              <a
                class="del_btn"
                :disabled="tableData.length == 1"
                style=""
              >删除</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </a-table>
  </div>
</template>
<script>
import moment from 'moment';
import { getLabelTypes, getMeetingRoomList } from '@/api/office/anualConference/index'
// 定期召开会议、计划会议
const meetTypeMap = {
  'dq': '定期召开会议',
  'jh': '计划会议'
}
const addressData = [
  { name: '东楼401', id: 'dl401' },
  { name: '东楼402', id: 'dl402' },
  { name: '东楼403', id: 'dl403' }
]
// 本地会议、视频会议
const formMap = {
  'bd': '本地会议',
  'sp': '视频会议'
}
const columns = [
  {
    title: '序号',
    width: '65px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    titleName: '会议名称',
    dataIndex: 'meetingName',
    width: '200px',
    slots: { title: 'meetingNameTitle' },
    scopedSlots: { customRender: 'meetingName' },
    editType: 'input'
  },
  {
    titleName: '会议类型',
    dataIndex: 'meetingType',
    width: '140px',
    slots: { title: 'meetingTypeTitle' },
    scopedSlots: { customRender: 'meetingType' },
    editType: 'select',
    selectData: [] //meetTypeMap
  },
  {
    titleName: '计划召开时间',
    dataIndex: 'planTime',
    width: '130px',
    slots: { title: 'planTimeTitle' },
    scopedSlots: { customRender: 'planTime' },
    editType: 'date'
  },
  {
    titleName: '会期(天)',
    dataIndex: 'session',
    width: '110px',
    slots: { title: 'sessionTitle' },
    scopedSlots: { customRender: 'session' },
    editType: 'number'
  },
  {
    titleName: '计划召开地点',
    dataIndex: 'meetingRoom',
    width: '120px',
    slots: { title: 'meetingRoomTitle' },
    scopedSlots: { customRender: 'meetingRoom' },
    editType: 'select',
    selectData: []
  },
  {
    titleName: '会议形式',
    dataIndex: 'meetingForm',
    width: '120px',
    slots: { title: 'meetingFormTitle' },
    scopedSlots: { customRender: 'meetingForm' },
    editType: 'select',
    selectData: []//formMap
  },
  {
    titleName: '会议规模(人)',
    dataIndex: 'meetingScale',
    width: '110px',
    slots: { title: 'meetingScaleTitle' },
    scopedSlots: { customRender: 'meetingScale' },
    editType: 'number'
  },
  {
    titleName: '会议预算(元)',
    dataIndex: 'meetingBudget',
    width: '120px',
    slots: { title: 'meetingBudgetTitle' },
    scopedSlots: { customRender: 'meetingBudget' },
    editType: 'number',
    minNumber: 0
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '80px',
    align: 'center',
    scopedSlots: { customRender: 'operation' },
  }
];
// const operation = {
//   title: '操作',
//   dataIndex: 'operation',
//   width: '80px',
//   align: 'center',
//   scopedSlots: { customRender: 'operation' },
// }

export default {
  name: 'EditableTable',
  props: {
    editable: {
      type: Boolean,
      default() {
          return true
      }, 
    },
    info: {
      type: Array,
      default() {
          return []
      }, 
    }
  },
  data() {
    return {
      cacheData: [], //defaultData.map(item => ({ ...item })),
      tableData: [],//defaultData,
      defaultColumns: columns,
      formMap,
      meetTypeMap,
      rowKey: 'id',
      editingKey: '',
      activeKey: []
    };
  },
  beforeCreate() {
  },
  created() {
    if (this.editable) {
      this.getLabelTypes(7, 'meetingType');
      this.getLabelTypes(8, 'meetingForm');
      this.getMeetingRoomList();
    }
    this.tableData = this.info;
    this.cacheData = this.info;
    // console.log(this.info)
  },
  computed: {
    columns() {
      const data = this.defaultColumns.filter((item, index) => { return item.dataIndex != 'operation'});
      let result = this.editable ? this.defaultColumns : data;
      // console.log(result)
      return result
    },
    year() {
      return Number(this.$route.query.year);
    }
  },
  mounted() {
    // console.log(this.cacheData)
  },
  methods: {
    moment,
    disabledDate(current) {
      const year = this.$route.query.year;
      return current && (current < moment(this.year.toString()) || current > moment((this.year + 1).toString()))
    },
    integerFormat(v, t) {
      let count = 0;
      if (t=='meetingBudget') {
        return (v && !isNaN(Number(v))) ? Number(v).toFixed(2) : ''
      }
      return (v && !isNaN(Number(v))) ? Number(v).toFixed(count) : ''
    },
    getLabelTypes(type, base) {
      let param = {
        "pageNo": 0,
        "pageSize": 100,
        "query": {
          "type": type
        }
      }
      getLabelTypes(param).then((res) => {
        if (res && res.code == 200) {
          this.defaultColumns.map((item, index) => {
            if (item.dataIndex == base) {
              item.selectData = res.data;
            }
            return item
          })
        }
      })
    },
    async getMeetingRoomList() {
      let param = {pageNo: 1, pageSize: 100, query: {enable: true, unitId: this.$userInfo().currentPost.id}}// 
      let res = await getMeetingRoomList(param);
      if (res && res.code == 200) {
        this.defaultColumns.map((item, index) => {
          if (item.dataIndex == 'meetingRoom') {
            item.selectData = res.data;
          }
          return item
        })
      }
    },
    createRandomId() {
      return (Math.random()*10000000).toString(16).substr(0,4)+''+(new Date()).getTime()+''+Math.random().toString().substr(2,5);
    },
    addrow() {
      let id = this.createRandomId();
      this.tableData.push({
        id: id,
        meetingName: null,
        meetingType: null,
        planTime: null,
        session: null,
        meetingRoom: null,
        meetingForm: null,
        meetingScale: null,
        meetingBudget: null
      });
      const newCacheData = [...this.tableData];
      this.cacheData = newCacheData;
    },
    validate() {
      let err = '';
      const newData = [...this.tableData];
      if (newData.length == 0) {
        err = '请至少填写一条数据！';
      } else {
        newData.forEach((item, index) => {
          for (let idx in item) {
            if (idx == 'id' || idx == 'status') continue;
            let key = item.id + idx;
            if (!item[idx] || (typeof item[idx] == 'object' && Object.keys(item[idx]).length == 0)) {
              this.$refs[key] && this.$refs[key][0].classList.add('validateError')
              err = '请填写完整再提交！';
            } else {
              this.$refs[key] && this.$refs[key][0].classList.contains('validateError') && this.$refs[key][0].classList.remove('validateError')
            }
          }
        })
      }
      return new Promise((resolve, reject) => {
        resolve(err)
      })
    },
    getPopupContainer(triggerNode) {
      return document.body;
    },
    getAddressData() {
      const data = addressData;
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(data)
        }, 3000)
      })
    },
    handleChange(value, key, column, type) {
      // console.log(value, key, column)
      const newData = [...this.tableData];
      const target = newData.filter(item => key === item[this.rowKey])[0];
      // console.log(target)
      if (target) {
        target[column] = value;
        this.tableData = newData;
        this.$emit('update:info', this.tableData)
        if (!value) {
          this.$refs[key + column][0].classList.add('validateError')
        } else {
          this.$refs[key + column] && this.$refs[key + column][0].classList.contains('validateError') && this.$refs[key + column][0].classList.remove('validateError')
        }
      }
    },
    // edit(key) {
    //   console.log(key)
    //   const newData = [...this.tableData];
    //   const target = newData.filter(item => key === item[this.rowKey])[0];
    //   console.log(target)
    //   this.editingKey = key;
    //   if (target) {
    //     target.editable = true;
    //     this.tableData = newData;
    //   }
    // },
    // save(key) {
    //   const newData = [...this.tableData];
    //   const newCacheData = [...this.cacheData];
    //   const target = newData.filter(item => key === item[this.rowKey])[0];
    //   const targetCache = newCacheData.filter(item => key === item[this.rowKey])[0];
    //   console.log(target)
    //   let validateStatus = false;
    //   for (let idx in target) {
    //     if (!target[idx]) {
    //       this.$refs[key + idx][0].classList.add('validateError')
    //       console.log(this.$refs[key + idx][0])
    //       validateStatus = true;
    //     } else {
    //       this.$refs[key + idx] && this.$refs[key + idx][0].classList.contains('validateError') && this.$refs[key + idx][0].classList.remove('validateError')
    //     }
    //   }
    //   if (validateStatus) {
    //     this.$message.error('请填写完整')
    //     // return
    //   };
    //   if (target && targetCache) {
    //     delete target.editable;
    //     this.tableData = newData;
    //     Object.assign(targetCache, target);
    //     this.cacheData = newCacheData;
    //   }
    //   this.editingKey = '';
    // },
    // cancel(key) {
    //   const newData = [...this.tableData];
    //   const target = newData.filter(item => key === item[this.rowKey])[0];
    //   this.editingKey = '';
    //   if (target) {
    //     Object.assign(target, this.cacheData.filter(item => key === item[this.rowKey])[0]);
    //     delete target.editable;
    //     this.tableData = newData;
    //   }
    // },
    del(key) {
      const data = [...this.tableData];
      const newData = data.filter(item => key !== item[this.rowKey]);
      this.editingKey = '';
      this.tableData = newData;
      this.cacheData = newData
      this.$emit('update:info', newData)
    }
  },
};
</script>
<style lang="less" scoped>
.editable-row-operations a {
  // margin-right: 8px;
}
/deep/ .ant-table-small > .ant-table-content > .ant-table-body {
  margin: 0;
}
.validateError /deep/ .ant-calendar-picker-input,
.validateError /deep/ .ant-select-selection,
.validateError .ant-input-number,
.validateError .ant-input,
{
  border-color: #f5222d;
}
.del_btn {
  color: #FF4D4F;
}
.del_btn[disabled] {
  color: #00000040;
}
</style>

